package com.kerbores.wzcc;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.kerbores.framworks.AsyncUrlPoster;
import com.kerbores.framworks.UrlPostHandler;

public class MainActivity extends FragmentActivity {
	
	private Context context;
	
	/**
	 * 省份下拉
	 */
	private Spinner privinces;
	/**
	 * 城市下拉
	 */
	private Spinner citys;
	/**
	 * 车辆类型下拉
	 */
	private Spinner types;
	/**
	 * 车牌号编辑框
	 */
	private EditText platev;
	/**
	 * 发动机号编辑框
	 */
	private EditText enginev;
	/**
	 * 提交按钮
	 */
	private Button submit;

	private NutMap data;
	private NutMap typeData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		getActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.actionbar_bg));
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		setContentView(R.layout.activity_main);

		context = this;
		initWidgets();// 加载控件
		initSpinners();// 加载下拉数据
		bindClick();// 绑定按钮的点击事件

		platev.setText("贵A19X37");
		enginev.setText("89541W");
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	

	/**
	 * 初始化下拉框们
	 */
	private void initSpinners() {
		initProvinces();// 省份 城市
		initTypes();
	}

	/**
	 * 
	 */
	private void initTypes() {
		new AsyncUrlPoster("http://apis.haoservice.com/weizhang/hpzl", "key=8ff45540c1364ad6b1b0d7479bf3d1f8", new UrlPostHandler() {

			@Override
			public void handleMessage(Message msg) {
				typeData = Lang.map(msg.getData().get("info").toString());
				System.out.println(typeData);
				if (typeData.getInt("error_code") != 0) {
					Toast.makeText(context, typeData.getString("reason"), Toast.LENGTH_SHORT).show();
				} else {
					List<String> types_ = new ArrayList<String>();
					types_.add("选择车辆类型");
					for (NutMap map : typeData.getArray("result", NutMap.class)) {
						types_.add(map.getString("car"));
					}
					types.setAdapter(getAdapter(types_));
				}
			}
		}).start();
	}

	/**
	 * 初始化省份
	 */
	private void initProvinces() {
		new AsyncUrlPoster("http://apis.haoservice.com/weizhang/citys", "key=8ff45540c1364ad6b1b0d7479bf3d1f8", new UrlPostHandler() {
			@Override
			public void handleMessage(Message msg) {
				data = Lang.map(msg.getData().get("info").toString());
				if (data.getInt("error_code") != 0) {
					Toast.makeText(context, data.getString("reason"), Toast.LENGTH_SHORT).show();
				} else {
					List<String> provinces_ = new ArrayList<String>();
					provinces_.add("选择省份");
					for (NutMap map : data.getArray("result", NutMap.class)) {
						provinces_.add(map.getString("province"));
					}
					privinces.setAdapter(getAdapter(provinces_));
					privinces.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> sp, View view, int arg2, long arg3) {
							String city = "" + sp.getSelectedItem().toString();
							List<String> citys_ = new ArrayList<String>();
							citys_.add("选择城市");
							for (Map m : (List<Map>) data.get("result")) {
								if (Strings.equals(m.get("province").toString(), city)) {
									for (Map cm : (List<Map>) m.get("citys")) {
										citys_.add(cm.get("city_name") + "");
									}
								}
								citys.setAdapter(getAdapter(citys_));
							}
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
						}
					});
				}
			}
		}).start();
	}

	/**
	 * 初始化页面控件
	 * 
	 * @param rootView
	 */
	private void initWidgets() {
		privinces = (Spinner)findViewById(R.id.privince);
		citys = (Spinner)findViewById(R.id.city);
		types = (Spinner) findViewById(R.id.type);
		platev = (EditText)findViewById(R.id.platev);
		enginev = (EditText)findViewById(R.id.enginev);
		submit = (Button)findViewById(R.id.submit);
	}

	/**
	 * 
	 */
	private void bindClick() {
		submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				
				String province = privinces.getSelectedItem() == null ? "" : privinces.getSelectedItem().toString();
				String city = citys.getSelectedItem() == null ? "" : citys.getSelectedItem().toString();
				String type = types.getSelectedItem() == null ? "" : types.getSelectedItem().toString();
				String plate = platev.getText().toString();
				String engine = enginev.getText().toString();
				
				String cityCode = getCityCode(province, city);
				NutMap pa = new NutMap();
				pa.put("key", "8ff45540c1364ad6b1b0d7479bf3d1f8");
				pa.put("city", cityCode);
				pa.put("hphm", plate);
				pa.put("hpzl", getTypeCode(type));
				pa.put("engineno", engine);
				// http://apis.haoservice.com/weizhang/query
				new AsyncUrlPoster("http://apis.haoservice.com/weizhang/query", pa, new UrlPostHandler() {

					@Override
					public void handleMessage(Message msg) {
						NutMap result = Lang.map(msg.getData().get("info").toString());
						if (result.getInt("error_code") == 0) {
							HashMap result_ = null;
							List<Map<String,String>> recode = null;
							if ((result_ = (HashMap) result.get("result")) != null && (recode = (List<Map<String,String>>) result_.get("lists")) != null && recode.size() > 0) {
								Intent intent = new Intent();
								intent.setClass(context, ResultActivity.class);
								intent.putExtra("result", (Serializable)recode);
								startActivity(intent);
							} else {
								Toast.makeText(context, "查询成功,没有违章记录", Toast.LENGTH_SHORT).show();
							}
						} else {
							Toast.makeText(context, result.getString("reason"), Toast.LENGTH_SHORT).show();
						}
						// TODO 用结果渲染Listview 显示违章信息概要情况 点击webview 用dialog
						// 显示一条违章详情

					}
				}).start();
			}

			private String getTypeCode(String type) {
				for (NutMap map : typeData.getArray("result", NutMap.class)) {
					if (Strings.equals(map.getString("car"), type)) {
						return map.getString("id");
					}
				}
				return "";
			}

			private String getCityCode(String province, String city) {
				for (NutMap map : data.getArray("result", NutMap.class)) {
					if (Strings.equals(map.getString("province"), province)) {
						for (Map c : (List<Map>) map.get("citys")) {
							if (Strings.equals(c.get("city_name").toString(), city)) {
								return c.get("city_code").toString();
							}
						}
					}
				}
				return "";
			}
		});
	}
	
	/**
	 * Spinner适配器
	 * @param listItems
	 * @return
	 */
	private ArrayAdapter<String> getAdapter(List<String> listItems){
		ArrayAdapter<String>  adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item, listItems);
		adapter.setDropDownViewResource(R.layout.custom_spinner_down);																				
		return adapter;
	}
}
